<template>
    <div class="main">
        <my-top-nav></my-top-nav>

        <div class="center_context">
            <!--地图：哈哈，精彩内容开始辽……-->
            <mapgis-web-map
                    id="map"
                    class="main"
                    :mapStyle="mapStyle"
                    :zoom="mapZoom"
                    :center="outerCenter"
                    :crs="mapCrs"
                    @load="onMapLoaded"
            >
                <mapgis-rastertile-layer
                        layerId="天地图影像"
                        url="http://t0.tianditu.com/DataServer?T=img_w&L={z}&Y={y}&X={x}&tk=9c157e9585486c02edf817d2ecbc7752"
                />
                <mapgis-rastertile-layer
                        layerId="天地图矢量"
                        url="http://t0.tianditu.com/DataServer?T=vec_w&L={z}&Y={y}&X={x}&tk=9c157e9585486c02edf817d2ecbc7752"
                />
                <mapgis-rastertile-layer
                        layerId="天地图注记"
                        url="http://t0.tianditu.com/DataServer?T=cia_w&L={z}&Y={y}&X={x}&tk=9c157e9585486c02edf817d2ecbc7752"
                />
                <!--<mapgis-igs-doc-layer
                        :layer="layer"
                        :layerId="layerId"
                        :sourceId="sourceId"
                        :ip="igsDocIp"
                        :port="igsDocPort"
                        :serverName="igsDocName"
                >
                </mapgis-igs-doc-layer>-->
                <!--图层3：校友分布1-->
                <mapgis-igs-doc-layer
                        :layer="layer3"
                        :layerId="layerId3"
                        :sourceId="sourceId3"
                        :ip="igsDocIp3"
                        :port="igsDocPort3"
                        :serverName="igsDocName3"
                >
                </mapgis-igs-doc-layer>

                <mapgis-igs-doc-layer
                        :layer="layer2"
                        :layerId="layerId2"
                        :sourceId="sourceId2"
                        :ip="igsDocIp2"
                        :port="igsDocPort2"
                        :serverName="igsDocName2"
                >
                </mapgis-igs-doc-layer>

                <!--地图文档（图层列表）控件-->
                <mapgis-document>
                    <!--:wrapperStyle="{borderRadius:'20px',backgroundColor:'green',width:'300px'}"-->
                </mapgis-document>

                <!--导航控件-->
                <mapgis-navigation showCompass showZoom />

                <!--全屏组件-->
                <mapgis-fullscreen position="top-right"/>

                <!--自定义比例尺控件-->
                <mapgis-custom-scale :outStyle='{"position":"absolute","left":"10px","bottom":"60px","width":"220px"}' />

                <!--鹰眼控件-->
                <mapgis-hawkeye v-if="isHawkeyeShow"/>

                <!--地图状态栏控件-->
                <div v-if="isStateShow" style="width:840px;height:30px;background-color:rgba(0,128,0,.06);position:absolute;bottom:65px;left:400px;z-index:2000;">
                    <!--<mapgis-state v-if="isStateShow" :default="false" scale level lng lat />-->
                    <mapgis-state :default="false">
                        <template v-slot:default="{state}">
                            <mapgis-ui-input-group size="default" class="mapgis-test-2d-statebar_my">
                                <mapgis-ui-input addon-before="级别" :value="state.level" />
                                <mapgis-ui-input addon-before="比例尺" :value="state.scale" />
                                <mapgis-ui-input addon-before="经度" :value="state.lng" />
                                <mapgis-ui-input addon-before="纬度" :value="state.lat" />
                            </mapgis-ui-input-group>
                        </template>
                    </mapgis-state>
                    <!--position="top-right"-->
                </div>

                <!--地图量测（测长度、测面积）-->
                <div style="width:300px;height:30px;background-color:rgba(0,128,0,.01);position:absolute;top:20px;left:250px;z-index:1000;">
                    <mapgis-measure enableControl isAdvanceControl position="top-right" />
                </div>

            </mapgis-web-map>
        </div>
    </div>
</template>


<script>
    import TopNav from '../components/TopNav.vue';

    import mapboxgl from '@mapgis/mapbox-gl'

    import Mapbox from '@mapgis/mapbox-gl'
    import { MapboxMap, MapboxIgsDocLayer } from '@mapgis/webclient-vue-mapboxgl'
    import MapgisDocument from "../../node_modules/@mapgis/webclient-vue-mapboxgl/src/components/UI/document/Document";
    import MapgisUiInputGroup from "../../node_modules/@mapgis/webclient-vue-ui/src/components/input/Group";


    export default {
        components: {
            MyTopNav:TopNav,
            MapgisUiInputGroup,
            MapgisDocument,
            MapboxMap, MapboxIgsDocLayer
        },
        data () {
            return {
                mapStyle: {
                    // 设置版本号，一定要设置
                    version: 8,
                    // 添加来源
                    sources: {},
                    // 设置加载并显示来源的图层信息
                    layers: []
                }, // 地图样式
                mapZoom: 6.25, // 地图初始化级数
                //outerCenter: [12389919,4341988], // 地图显示中心
                //outerCenter: [12286207.606220635,4216509.8240411337], // 地图显示中心
                //outerCenter: [-77.04, 38.907], // 地图显示中心  西安（看作是中国地图的几何中心）
                outerCenter: [108.94, 34.27], // 地图显示中心  西安（看作是中国地图的几何中心）
                //outerCenter: [100.354465, 30.488737], // 测试
                //outerCenter: [111.34, 36.22], // 地图显示中心（临汾）
                mapCrs: 'EPSG:3857',

                layerId: 'igsLayer_layerId',
                sourceId: 'igsLayer_sourceId',
                layer: {}, // 图层配置信息
                igsDocIp: 'jlu3s.com', // igs服务ip
                igsDocPort: '8015', // igs服务port
                igsDocName: 'LinFen01_3857', // igs地图服务名

                layerId2: '临汾专题图2',
                sourceId2: 'igsLayer_sourceId2',
                layer2: {}, // 图层配置信息
                igsDocIp2: 'jlu3s.com', // igs服务ip
                igsDocPort2: '8015', // igs服务port
                igsDocName2: 'LinFen02_3857', // igs地图服务名

                layerId3: '专题图（1）',
                sourceId3: 'igsLayer_sourceId3',
                layer3: {}, // 图层配置信息
                igsDocIp3: 'jlu3s.com', // igs服务ip
                igsDocPort3: '8015', // igs服务port
                //igsDocName3: 'dxgs_shoolmates1', // igs地图服务名
                igsDocName3: 'schoolmate_edu_1', // igs地图服务名

                //isDrawerVisible: false, //左侧导航栏抽屉默认不显示

                isHawkeyeShow: true, //控制鹰眼是否显示，默认不显示

                isStateShow: true, //控制地图状态栏，默认false不显示
            }
        },
        created() {
            // 在组件中使用mapbox-gl.js的脚本库功能
            this.mapbox = Mapbox;

            this.map = null;
        },
        methods:{
            onMapLoaded(event) {
                this.map = event.map;
                let map = this.map;

                //#region mapgis的要素查询
                AttQuery()
                function AttQuery(){
                    //let that = this;
                    //let sxcxArr = that.MYCONFIG.attrQuery[that.pn]; //有值，或undefined
                    //console.log(sxcxArr,"that.MYCONFIG.attrQuery[that.pn]",86543);

                    //clearA();
                    //显示进度条
                    //startPressBar();

                    //初始化查询结构对象，设置查询结构包含几何信息
                    var queryStruct = new Zondy.Service.QueryFeatureStruct();
                    //是否包含几何图形信息
                    queryStruct.IncludeGeometry = true;
                    //是否包含属性信息
                    queryStruct.IncludeAttribute = true;
                    //是否包含图形显示参数
                    queryStruct.IncludeWebGraphic = false;
                    //实例化查询参数对象
                    var queryParam = new Zondy.Service.QueryParameter({
                        resultFormat: "json",
                        struct: queryStruct
                    });
                    //设置查询分页号
                    queryParam.pageIndex = 0;
                    //设置查询要素数目
                    queryParam.recordNumber =20;
                    //设置属性条件
                    //queryParam.where = document.getElementById("Conditions").value;
                    queryParam.where = "OID>'1'";
                    //queryParam.where = that.attQueryConditions;
                    console.log(queryParam,14)
                    //实例化地图文档查询服务对象
                    //var queryService = new Zondy.Service.QueryDocFeature(queryParam, "gn_dish", 1, { //①查询参数信息,②地图文档名称,③图层索引号,④{属性键值对}
                    var queryService = new Zondy.Service.QueryDocFeature(queryParam, "schoolmate_edu_1", 1, { //①查询参数信息,②地图文档名称,③图层索引号,④{属性键值对}
                        //ip: "develop.smaryun.com",
                        //port: "6163"    //访问IGServer的端口号，.net版为6163，Java版为8089
                        //ip: "jlu3s.com",
                        //port: "7035"    //访问IGServer的端口号，.net版为6163，Java版为8089
                        ip: "jlu3s.com",
                        port: "8015"    //访问IGServer的端口号，.net版为6163，Java版为8089
                    });
                    //执行查询操作，querySuccess为查询回调函数
                    queryService.query(querySuccess, queryError);

                    //查询失败回调
                    /*function queryError(e) {
                     //停止进度条
                     stopPressBar();
                     }*/

                    //查询成功回调
                    var drawLayer = null;
                    //清除客户端查询结果信息
                    function clearA() {
                        //停止进度条
                        stopPressBar();
                        if (drawLayer) {
                            //移除高亮显示结果图层drawLayerr
                            map.removeLayer(drawLayer);
                        }
                        else
                            return;
                    }
                    /*======进度条======*/
                    //停止进度条
                    function stopPressBar() {
                        document.getElementById("preview").style.display = "none";
                    }
                    //开始进度条动画
                    function startPressBar() {
                        document.getElementById("preview").style.display = "block";
                    }
                }


                /** 查询成功回调函数
                 *  @param {json对象} result 获取结果对象
                 */
                function querySuccess(result) {
                    console.log("查询成功啦！",result,333)

                    //墨卡托转经纬度
                    function mktlng(poi){
                        var lnglat = {};
                        //lnglat.lng = poi.x/20037508.34*180;
                        lnglat.x = poi.x/20037508.34*180;
                        var mmy = poi.y/20037508.34*180;
                        //lnglat.lat = 180/Math.PI*(2*Math.atan(Math.exp(mmy*Math.PI/180))-Math.PI/2);
                        lnglat.y = 180/Math.PI*(2*Math.atan(Math.exp(mmy*Math.PI/180))-Math.PI/2);
                        return lnglat;
                    }
                    //停止进度条
                    //stopPressBar();
                    //获取查询到的结果数组,ploygonArr的个数即为查询到的结果数
                    var ploygonArr = result.SFEleArray;
                    var FldNameArr = result.AttStruct.FldName;
                    console.log(FldNameArr,212121)
                    var features = [];
                    for (let i = 0; i < ploygonArr.length; i++) {
                        //获取要素几何数组
                        let Dot = ploygonArr[i].fGeom.PntGeom[0].Dot;
                        console.log(Dot,343434)

                        Dot = mktlng(Dot); //注意：需要把Web墨卡托反转为经纬度，下方才能geojson点数据显示在地图上
                        console.log(Dot,434343)

                        var finaldot = [];
                        //finaldot.push([Dot.x, Dot.y]); //对于Point，不要乱套[]多加一层数组导致最后在地图上渲染不出来
                        finaldot.push(Dot.x, Dot.y);

                        let AttArr_Of_Dot = ploygonArr[i].AttValue;
                        console.log(ploygonArr,AttArr_Of_Dot,210210)
                        let descContext = "";
                        let trs = '';
                        for(let i=0; i<FldNameArr.length; i++){
                            //descContext += FldNameArr[i] + " : " + AttArr_Of_Dot[i] + '<br/> \n\n'; //【勉强可行】
                            trs += arrEleToTR(FldNameArr[i],AttArr_Of_Dot[i]);
                        }
                        descContext = arrEleToTable(trs);
                        console.log(descContext,357753)

                        function arrEleToTR(arr1,arr2){
                            let tr='';
                            /*for(let i=0;i<arr1.length;i++){
                             trs += `<tr><td>${arr1[i]}</td><td>${arr2[i]}</td></tr>`;
                             }*/
                            tr += `<tr><td>${arr1}</td><td>${arr2}</td></tr>`;
                            return tr;
                        }
                        function arrEleToTable(trs){
                            //console.log(trs,96432)
                            let html = '';
                            html += `<div class="myAttTable">`;
                            //html += `<i class="icon"></i>`
                            html += `<table>`;
                            html += `<tr><th>属性名称</th><th>属性值</th></tr>`;
                            html += trs;
                            html += `</table>`;
                            html += `</div>`;
                            return html;
                        }


                        let descArr = [];
                        for(let i=0; i<FldNameArr.length; i++){
                            descArr.push({"fn":FldNameArr[i],"fv":AttArr_Of_Dot[i]});
                        }
                        //console.log(descArr,135135)

                        let feature = {
                            "type": "Feature",
                            "geometry": {
                                "type": "Point",
                                "coordinates": finaldot   //这里不要给finadot加[]多套一层数组，导致在地图上渲染不出来
                            },
                            "properties":{
                                "description":descContext //组合文本描述法 【勉强可行】
                                //"description": descArr  //数组描述法【初步以为有利于下面放到表格里，后来发现不行】
                            }
                        }
                        features.push(feature);
                    }


                    // Load an image from an external URL.
                    map.loadImage(
                        //'http://jlu3s.com:7037/dxgs_pic/rw.png',
                        //'https://docs.mapbox.com/mapbox-gl-js/assets/cat.png',
                        //'../assets/logo.png',//这种方式行不通，即使改为@/assets/的方式也引用不到
                        //rw2的base64
                        '',
                        (error, image) => {
                            if (error) throw error;

                            // Add the image to the map style.
                            //map.addImage('dxgs_pic_rw', image);
                            map.addImage('cat', image);
                        });

                    //单个点试验
                    /*let testabc = [];
                    testabc.push(100.354465, 30.488737);
                    let ft = {
                        "type": "Feature",
                        "geometry": {
                            "type": "Point",
                            "coordinates": testabc
                        },
                        'properties': {
                            'description':
                                '<strong>Truckeroo</strong><p><a href="http://www.truckeroodc.com/www/" target="_blank">Truckeroo</a> brings dozens of food trucks, live music, and games to half and M Street SE (across from Navy Yard Metro Station) today from 11:00 a.m. to 11:00 p.m.</p>',
                            //'icon': 'music-15'
                            'icon': 'https://docs.mapbox.com/mapbox-gl-js/assets/cat.png'
                        },
                    }
                    features.push(ft);*/

                    //用geojson创建一个多边形
                    var geometryPolygon = {
                        "type": "FeatureCollection",
                        "features": features
                    };
                    var source = {
                        "type": "geojson",
                        "data": geometryPolygon
                    };

                    map.addLayer({
                        //此id可随意设置，但是要唯一
                        "id": "highlayer",
                        //指定类型
                        "type": "symbol",
                        //"type": "circle",
                        //设置数据来源
                        "source": source,
                        'layout': {
                            //'icon-image': 'dxgs_pic_rw', // reference the image
                            'icon-image': 'cat', // reference the image
                            'icon-size': 1.0
                        }
                        /*'paint': {
                            'circle-radius': 10,
                            'circle-color': '#b304b4'
                        },
                        'filter': ['==', '$type', 'Point']*/
                    });
                    //stopPressBar()
                }

                /** 查询失败回调函数
                 */
                function queryError() {
                    //停止进度条
                    //stopPressBar();
                    alert("查询失败！");
                }
                //#endregion

                // Change the cursor to a pointer when the mouse is over the places layer.
                map.on('mouseenter', 'highlayer', () => {
                    map.getCanvas().style.cursor = 'pointer';
                });

                // Change it back to a pointer when it leaves.
                map.on('mouseleave', 'highlayer', () => {
                    map.getCanvas().style.cursor = '';
                });
                map.on('click','highlayer', (e) => {

                    const coordinates = e.features[0].geometry.coordinates.slice();
                    const description = e.features[0].properties.description; //适用于文字描述法（带换行）

                    /*const description = arrEleToTable(e.features[0].properties.description); //适用于文字描述法（带换行）
                     console.log(e.features[0].properties.description,606)
                     console.log(description,616) //但传到这里之后，properties就不是数组了（而是String)
                     function arrEleToTable(arrs){
                     console.log(arrs,96432)
                     let html = '';
                     html += `<div class="divClass">`;
                     //html += `<i class="icon"></i>`
                     html += `<table>`;
                     html += `<tr><th>属性名称</th><th>属性值</th></tr>`;
                     for(let i=0;i<arrs.length;i++){
                     html += `<tr><td>${arrs[i].fn}</td><td>${arrs[i].fv}</td></tr>`;
                     }
                     html += `</table>`;
                     html += `</div>`;
                     return html;
                     }*/

                    // Ensure that if the map is zoomed out such that multiple
                    // copies of the feature are visible, the popup appears
                    // over the copy being pointed to.
                    while (Math.abs(e.lngLat.lng - coordinates[0]) > 180) {
                        coordinates[0] += e.lngLat.lng > coordinates[0] ? 360 : -360;
                    }

                    new mapboxgl.Popup({maxWidth:'500px'})
                        .setLngLat(coordinates)
                        .setHTML(description)
                        .setMaxWidth("600px")
                        .addTo(map);
                });


            },
        }

    }
</script>

<style scoped>
    .mapgis-test-2d-statebar_my {
        display: flex;
    }
    .mapgis-test-2d-statebar_my span span span {
        width:40px;
    }

    /*首先给整个table表格的外边框加上左边框和上边框*/
    .myAttTable table {width: 350px;border-top: 1px solid #999;border-left: 1px solid #999;}
    /*再给table表格里的每个单元格添加下边框和右边框*/
    .myAttTable table td,th {/*padding: 10px 30px;*/border-bottom: 1px solid #999;border-right: 1px solid #999;}
    /*去掉单元格的间隙*/
    .myAttTable table {width: 350px;border-top: 1px solid #999;border-left: 1px solid #999;border-spacing: 0;/*去掉单元格间隙*/}
</style>